package com.virtium.vpm.dao.hibernate;

import java.util.List;

import org.hibernate.Session;
import com.virtium.vpm.dao.GenericDAO;
import com.virtium.vpm.dao.HibernateSessionFactory;


/**
 * Data access object (DAO) for domain model
 * @author MyEclipse Persistence Tools
 */
public class BaseHibernateDAO implements GenericDAO {
	protected Class persistentClass = null;
    protected Session hsession = null;
    
    
    public BaseHibernateDAO() {
    	
    };
    public Class getPersistentClass() {
    	return this.persistentClass;
    }
	public Session getSession() {
		if (this.hsession == null || !this.hsession.isOpen()) {    		
    		this.hsession = HibernateSessionFactory.getSession();
    	}    
    	return this.hsession;
	}
	public void closeSession() {
		if (this.hsession != null) {
	    	if (this.hsession.isOpen()) {
	    		System.out.println("**** Closing Hibernate Session ****");
	    		this.hsession.close();
	    	}
	    	else
	    		System.out.println("Hibernate Session is closed already...");
	    	
	    	this.hsession = null;
		}		
	}

	public Session currentSession(boolean enableFilter) {
		if (this.hsession == null || !this.hsession.isOpen()) {    		
    		this.hsession = HibernateSessionFactory.getSession();
    	}    
    	return this.hsession;
	}

	public List executeQuery(boolean enableFilter, String query) 
	throws DAOException {		
		List list = null;
		
		try {
			list = currentSession(enableFilter).createQuery(query).list();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			throw new DAOException(e.getMessage());
		}   
		
		return list;
	
	}
	
	protected void finalize() {  	
		System.out.println("Finalize() of class "+this.getClass().getName()+" is called...");
    	closeSession();
    }
	
}